<?php

namespace App\Repositories;

use App\Models\LoginLog;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Arr;
use Jenssegers\Agent\Agent;

/**
 * 登录日志仓储类
 * @package App\Repositories
 * @method Model|LoginLog|null getById(int $id): ?LoginLog
 * @method Model|LoginLog|null create(array $attributes): ?LoginLog
 */
class LoginLogRepository extends BaseRepository
{
    public function __construct(LoginLog $model)
    {
        parent::__construct($model);
    }

    public function log(array $data)
    {
        $agent = new Agent();
        $data['device'] = $agent->device();
        $data['browser'] = $agent->browser();
        $data['os'] = $agent->platform();
        return $this->query()->create($data);
    }

    public function pagination(array $params): LengthAwarePaginator
    {
        $query = $this->query();
        $keyword = Arr::get($params, 'keyword', '');
        if ($keyword) {
            $query->where(function ($query) use ($keyword) {
                $query->where('name', 'like', "%{$keyword}%")
                    ->orWhere('login_ip', 'like', "%{$keyword}%")
                    ->orWhere('browser', 'like', "%{$keyword}%")
                    ->orWhere('device', 'like', "%{$keyword}%")
                    ->orWhere('os', 'like', "%{$keyword}%");
            });
        }

        $startDate = Arr::get($params, 'startDate', '');
        $endDate = Arr::get($params, 'endDate', '');
        if ($startDate && $endDate) {
            $query->whereBetween('created_at', [$startDate . ' 00:00:00', $endDate . ' 23:59:59']);
        }

        return $query->orderBy('id', 'desc')->paginate(10)->through(fn(LoginLog $row) => [
            'id' => $row->id,
            'name' => $row->name,
            'status' => $row->status,
            'message' => $row->message,
            'login_ip' => $row->login_ip,
            'device' => $row->device,
            'browser' => $row->browser,
            'referer' => $row->referer,
            'os' => $row->os,
            'created_at' => $row->created_at->format('Y-m-d H:i:s'),
            'login_at' => $row->login_at,
        ]);
    }
}
